package com.im.db;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import com.core.sdk.core.LogUtil;
import com.im.model.XmppMessage;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.stmt.QueryBuilder;
import com.j256.ormlite.stmt.UpdateBuilder;
import com.j256.ormlite.stmt.Where;


public class XmppMessageDao {
	private final String tag = "XmppMessageDao";
	private Dao<XmppMessage, Integer> dao;

	public XmppMessageDao(DBHelper dbHelper) {
		try {
			dao = dbHelper.getDao(XmppMessage.class);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public XmppMessage createEntity(XmppMessage xm){
		try {
			dao.create(xm);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return xm;
	}

	/** 加载历史消息记录 */
	@SuppressWarnings("unchecked")
	public List<XmppMessage> getHistoryXmppMessage(String otherJID,long pageNo,long pageSize,long time) {
		List<XmppMessage> list = null ;
		try {
			QueryBuilder<XmppMessage, Integer> queryBuilder = dao.queryBuilder();
			queryBuilder.offset(pageNo*pageSize).limit(pageSize).orderBy("create_time", false);
			Where<XmppMessage, Integer> where = queryBuilder.where();
			
			where.and(
					where.eq("readed", true), 
					where.lt("create_time", time),
					where.or(where.eq("from_user", otherJID), where.eq("to_user", otherJID))
					);

			LogUtil.d(tag, "where=" + where.getStatement().replace("`", ""));
			list = where.query();
			if(list != null && list.size() >0){
				Collections.reverse(list);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		if(list == null)
			list = new ArrayList<XmppMessage>();
		return list;
	}
	
	/** 加载未读消息记录 */
	public List<XmppMessage> getUnreadXmppMessage(String otherJID) {
		List<XmppMessage> list = null ;
		try {
			QueryBuilder<XmppMessage, Integer> queryBuilder = dao.queryBuilder();
			queryBuilder.orderBy("create_time", true);
			Where<XmppMessage, Integer> where = queryBuilder.where();
			where.eq("from_user", otherJID).and().eq("readed", false);
			LogUtil.d(tag, "where=" + where.getStatement());
			list = where.query();
		} catch (Exception e) {
			e.printStackTrace();
		}
		if(list == null)
			list = new ArrayList<XmppMessage>();
		return list;
	}
	
	/** 标记为已读 */
	public void markToReadedById(int id) {
		try {
			UpdateBuilder<XmppMessage, Integer> update = dao.updateBuilder();
			update.updateColumnValue("readed", true);
			update.where().idEq(id);
			update.update();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/** 标记为已读 */
	public void markToReadedById(Object[] ids){
		try {
			UpdateBuilder<XmppMessage, Integer> update = dao.updateBuilder();
			update.updateColumnValue("readed", true);
			update.where().in("id",ids);
			update.update();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	

}
